<route lang="yaml">
  meta:
    title: 待卸货
</route>

<script setup lang="ts">
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { ref } from 'vue'

const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(1000) // 模拟总数据量

interface Project {
  id: string
  productId: string
  productName: string
  quantity: number
  supplierName: string
  price: number
  weight: number
  size: string
  status: StatusType
}

const searchKeyword = ref('')
// 修正状态类型定义
type StatusType = '待卸货' | '待确认' | '已卸货' | '已撤回'

// 修正颜色映射关系
const statusColors: Record<StatusType, 'success' | 'warning' | 'info' | 'danger'> = {
  待卸货: 'info',
  待确认: 'warning',
  已卸货: 'success',
  已撤回: 'danger',
}

const tableData = ref<Project[]>([
  {
    id: 'P001',
    productId: '1001',
    productName: '笔记本电脑',
    quantity: 50,
    supplierName: '上海电子科技',
    price: 6999.0,
    weight: 2.5,
    size: '35×25×3 cm',
    status: '待卸货',
  },
  // 其他示例数据可参照原有结构修改status为待卸货状态
])

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const selectedRows = ref<Project[]>([])

// 批量卸货确认
async function handleConfirm() {
  try {
    const validSelections = selectedRows.value.filter(item => item.status === '待卸货')

    if (validSelections.length === 0) {
      return ElMessage.warning('请至少选择一个待卸货的商品')
    }

    await ElMessageBox.confirm(
      `确定要批量确认 ${validSelections.length} 个商品的卸货吗？`,
      '批量卸货确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    validSelections.forEach((row) => {
      row.status = '待确认' // 修改状态为待确认
    })
    multipleTableRef.value?.clearSelection()
    ElMessage.success(`已确认 ${validSelections.length} 个商品卸货`)
  }
  catch {
    ElMessage.info('已取消操作')
  }
}

// 撤回操作
async function handleRecall() {
  try {
    const validSelections = selectedRows.value.filter(item => item.status === '已卸货')

    if (validSelections.length === 0) {
      return ElMessage.warning('请至少选择一个已卸货的商品')
    }

    await ElMessageBox.confirm(
      `确定要撤回 ${validSelections.length} 个商品的卸货状态吗？`,
      '撤回确认',
      {
        confirmButtonText: '确认撤回',
        cancelButtonText: '取消',
        type: 'error',
      },
    )

    validSelections.forEach((row) => {
      row.status = '已撤回'
    })
    multipleTableRef.value?.clearSelection()
    ElMessage.success(`已撤回 ${validSelections.length} 个商品`)
  }
  catch {
    ElMessage.info('已取消操作')
  }
}

// 单个商品最终操作
// async function handleRowOperation(row: Project) {
//   try {
//     const action = row.status === '待卸货' ? '确认卸货' : '撤回操作'

//     await ElMessageBox.confirm(
//       `确定要${action}【${row.productName}】吗？`,
//       `${action}确认`,
//       {
//         confirmButtonText: '确认',
//         cancelButtonText: '取消',
//         type: row.status === '待卸货' ? 'warning' : 'error',
//       },
//     )

//     row.status = row.status === '待卸货' ? '已卸货' : '已撤回'
//     ElMessage.success(`${action}成功`)
//   }
//   catch {
//     ElMessage.info('已取消操作')
//   }
// }

async function handleRowOperation(row: Project) {
  try {
    await ElMessageBox.confirm(
      `确定要完成【${row.productName}】的最终卸货确认吗？`,
      '最终确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    row.status = '已卸货'
    ElMessage.success('卸货最终确认成功')
  }
  catch {
    ElMessage.info('已取消操作')
  }
}
</script>

<template>
  <div>
    <FaPageMain>
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="primary" @click="handleConfirm">
            <el-icon><Check /></el-icon>
            <span class="ml-1">批量卸货</span>
          </el-button>
          <el-button
            type="danger"
            style="margin-left: 12px;"
            @click="handleRecall"
          >
            <el-icon><Refresh /></el-icon>
            <span class="ml-1">撤回操作</span>
          </el-button>
        </div>

        <div class="search-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称/ID"
            clearable
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <div class="table-wrapper">
        <ElTable
          ref="multipleTableRef"
          :data="tableData"
          row-key="id"
          style="width: 100%;"
          max-height="calc(100vh - 200px)"
          :fit="true"
          stripe
          @selection-change="(rows: Project[]) => selectedRows = rows"
        >
          <el-table-column
            type="selection"
            :selectable="(row: Project) => row.status === '待卸货' || row.status === '已卸货'"
          />
          <el-table-column prop="productId" label="商品ID" />
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column prop="supplierName" label="供应商" />
          <el-table-column prop="price" label="单价">
            <template #default="{ row }">
              ￥{{ row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(kg)" width="120" />
          <el-table-column prop="size" label="尺寸" width="150" />

          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="statusColors[row.status as StatusType]" effect="dark">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="row.status === '待确认'"
                type="primary"
                size="small"
                @click="handleRowOperation(row)"
              >
                确认卸货
              </el-button>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>
        </ElTable>
      </div>

      <div class="pagination-wrapper" float-right>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </FaPageMain>
  </div>
</template>

<style scoped>
/* 保持原有样式不变 */
.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.mb-4 {
  margin-bottom: 1rem;
}

.ml-1 {
  margin-left: 0.25rem;
}

.search-wrapper {
  display: flex;
  justify-content: flex-end;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 16px;
}
</style>
